package com.cysyz.mylib.dao.sqlcondspopulater.impl;


import com.cysyz.mylib.dao.sqlcondspopulater.SqlCondsPopulater;
import com.cysyz.mylib.dao.sqloperaterrevolver.SqlOperatorRevolver;
import com.cysyz.mylib.dao.sqloperaterrevolver.impl.InOperatorRevolver;
import com.cysyz.mylib.dao.sqloperaterrevolver.impl.SimpleOperatorRevolver;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by emall on 2014/7/29.
 */
public class SqlCondsPopulaterImpl implements SqlCondsPopulater {
    protected StringBuilder sqlBuilder;
    protected List<Object> params;
    List<SqlOperatorRevolver> sqlOperatorRevolvers = new ArrayList<SqlOperatorRevolver>();

    /*private String defaultColumnPrefix;*/

    public SqlCondsPopulaterImpl(StringBuilder sqlBuilder, List<Object> params) {
        this(sqlBuilder, params, false);
    }

    public SqlCondsPopulaterImpl(StringBuilder sqlBuilder, List<Object> params, boolean sqlHasWhere) {
        this.sqlBuilder = sqlBuilder;
        this.params = params;
        if (!sqlHasWhere) {
            sqlBuilder.append(" where 1=1 ");
        }

        setSqlOperators();
    }

    protected void setSqlOperators() {
        sqlOperatorRevolvers.add(new SimpleOperatorRevolver());
        sqlOperatorRevolvers.add(new InOperatorRevolver());
    }

    /**
     *
     * @param column
     * @param operator 操作符
     * @param value
     */
    @Override
    public void addCond(String column, String operator, Object value) {
        /*if (!MyAssert.isNullOrEmpty(defaultColumnPrefix)) {
            StringBuilder columnBuilder = new StringBuilder(defaultColumnPrefix);
            columnBuilder.append(".");
            columnBuilder.append(column);
            column = columnBuilder.toString();
        }*/
        if (value != null) {
            for (SqlOperatorRevolver sqlOperator : sqlOperatorRevolvers) {
                if (sqlOperator.support(sqlBuilder, params, column, operator, value)) {
                    sqlOperator.addCond(sqlBuilder, params, column, operator, value);
                    break;
                }
            }
        }
    }

    @Override
    public void addCond(String column, Object value) {
        this.addCond(column, "=", value);
    }





















    /*getter and setter*/

    public StringBuilder getSqlBuilder() {
        return sqlBuilder;
    }

    public void setSqlBuilder(StringBuilder sqlBuilder) {
        this.sqlBuilder = sqlBuilder;
    }

}
